package com.vader.admin.service.impl;

import com.vader.admin.client.DistributeIdClient;
import com.vader.admin.entity.DO.BaseTaskPublish;
import com.vader.admin.dao.BaseTaskPublishDao;
import com.vader.admin.service.BaseTaskPublishService;
import com.vader.common.entity.CommonResponse;
import com.vader.common.exception.BadRequestException;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;

import javax.annotation.Resource;

/**
 * 活动发布信息(BaseTaskPublish)表服务实现类
 *
 * @author Vader
 * @since 2021-10-06 12:46:39
 */
@Service("baseTaskPublishService")
public class BaseTaskPublishServiceImpl implements BaseTaskPublishService {
    @Resource
    private BaseTaskPublishDao baseTaskPublishDao;

    @Resource
    private DistributeIdClient distributeIdClient;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public BaseTaskPublish queryById(Long id) {
        return this.baseTaskPublishDao.queryById(id);
    }

    /**
     * 分页查询
     *
     * @param baseTaskPublish 筛选条件
     * @param pageRequest     分页对象
     * @return 查询结果
     */
    @Override
    public Page<BaseTaskPublish> queryByPage(BaseTaskPublish baseTaskPublish, PageRequest pageRequest) {
        long total = this.baseTaskPublishDao.count(baseTaskPublish);
        return new PageImpl<>(this.baseTaskPublishDao.queryAllByLimit(baseTaskPublish, pageRequest), pageRequest, total);
    }

    /**
     * 发布活动
     *
     * @param baseTaskPublish 实例对象
     * @return 实例对象
     */
    @Override
    public BaseTaskPublish insert(BaseTaskPublish baseTaskPublish) {
        CommonResponse<Long> id = distributeIdClient.getId();
        if (id.getCode() != 0) {
            throw new BadRequestException("生成活动ID异常");
        }
        baseTaskPublish.setId(id.getData());
        baseTaskPublish.setCompleted(0);
        baseTaskPublish.setCreateAt(System.currentTimeMillis());
        baseTaskPublish.setUpdateAt(System.currentTimeMillis());
        baseTaskPublish.setIsDeleted(0);
        this.baseTaskPublishDao.insert(baseTaskPublish);
        return baseTaskPublish;
    }

    /**
     * 修改数据
     *
     * @param baseTaskPublish 实例对象
     * @return 实例对象
     */
    @Override
    public BaseTaskPublish update(BaseTaskPublish baseTaskPublish) {
        this.baseTaskPublishDao.update(baseTaskPublish);
        return this.queryById(baseTaskPublish.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long id) {
        return this.baseTaskPublishDao.deleteById(id) > 0;
    }
}
